﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WMM.Tapioca.Instance;
using WMM.Tapioca.Taxonomy;
using WMM.Tapioca.Linkbase;
using System.Xml.Linq;

namespace WMM.Tapioca.Formula.Filters
{
    /// <summary>
    /// The dimension matching filter can be used to select facts that have 
    /// the same value for a specified XBRL Dimension
    /// </summary>
    public class MatchDimensionFilter : MatchFilter
    {
        private string dimension;

        /// <returns> The QName of the dimension in the XPath expression implied by a dimension matching filter
        /// is given by the @dimension attribute on the dimension matching filter. </returns>
        public string Dimension
        {
            get { return dimension; }
            set { dimension = value; }
        }

        /// <summary>
        /// Constructor.
        /// </summary>
        public MatchDimensionFilter(Resource resource)
            : base(resource)
        {          
            dimension = (string)resource.ResourceXElement.Attribute("dimension") ?? string.Empty;
        }


        public override List<FactItem> EvaluateFilter(VariableSet variableSet, List<FactItem> itemsToFilter, DTS dts)
        {
            this.dts = dts;
            namespaces = dts.DtsFormula.Namespaces;

            List<FactItem> itemListTemp = new List<FactItem>();

            foreach (FactItem itemToFilter in itemsToFilter)
            {
                List<FactItem> factItems = variableSet.variableItems[Variable];

                string dimensionQName = Dimension;

                for (int i = 0; i < factItems.Count; i++)
                {
                    if (Complement ? !ContainsDimension(itemToFilter.ContextRef, dimensionQName) :
                        ContainsDimension(itemToFilter.ContextRef, dimensionQName))
                    {
                        itemListTemp.Add(itemToFilter);
                        continue;
                    }
                }
            }

            return itemListTemp;
        }


        private bool ContainsDimension(Context context, string dimensionQName)
        {
            foreach (XElement explicitMember in context.ExplicitMembers)
            {
                string dimension = (string)explicitMember.Attribute("dimension") ?? string.Empty;

                if (dimensionQName.Equals(dimension))
                {
                    return true;
                }
            }

            foreach (XElement typedMember in context.TypedMembers)
            {
                string dimension = (string)typedMember.Attribute("dimension") ?? string.Empty;

                if (dimensionQName.Equals(dimension))
                {
                    return true;
                }
            }

            return false;
        }
    }
}
